package com.hecj.common.lib.encryption;

import com.hecj.common.lib.util.Constant;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;

/**
 * 说明：RAS加密解析工具类
 * author hecj
 */
public class RsaKit {

    /**
     * 解析
     * @param text
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws InvalidKeySpecException
     */
    public static String decode(String text)  {
        Base64 base64 = new Base64();
        if (StringUtils.isBlank(text)) {
            return "";
        }
        try{
            return EncryptionUtil.decrypt(base64.decode(text),
                    EncryptionUtil.getPrivateKey(Constant.PrivateKey));
        } catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException("RSA解密失败");
        }
        
    }

    /**
     * 加密
     * @param text
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws InvalidKeySpecException
     */
    public static String encode(String text) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
        if (StringUtils.isBlank(text)) {
            return "";
        }
        byte[] bytes = EncryptionUtil.encrypt(text, EncryptionUtil.getPublicKey(Constant.publicKey));
        return Base64Util.encodeBytes(bytes);
    }

}
